package demo.session;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

//购物车类
@WebServlet(name = "CartServlet",urlPatterns = "/CartServlet")
public class CartServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter out = resp.getWriter();
        //变量cart引用用户的购物车
        List<Cake> cart = null;
        //变量pruFlag标记用户是否买过商品
        boolean purFlag = true;
        //获得用户的session
        HttpSession session = req.getSession(false);
        //如果session为null，purFlag置为false
        if (session == null){
            purFlag = false;
        }else {
            //获得用户购物车
            cart = (List) session.getAttribute("cart");
            //如果用的购物车为null，purFlag置为false
            if (cart == null){
                purFlag = false;
            }
        }
        /**
         * 如果purFlag为false，表明用户没有购买蛋糕 重定向到ListServlet页面
         *
         */
        if (!purFlag){
            out.write("对不起！您还没有购买任何商品！ <br>");

        }else {
            //否则显示用户购买蛋糕信息
            out.write("您购买的蛋糕有：<br>");
            double price = 0;
            for (Cake cake : cart){
                out.write(cake.getName() + "<br>");
            }
        }
    }
}
